<script setup>
import _ from 'lodash'
import {isGroup, isMbRoot, isApp, canEdit} from './common.js';
import mbformGroup from './mbform-group.vue';
import mbformMb from './mbform-mb.vue';
import {onMounted, ref, watch} from "vue";
import {api} from "@jzl/api";
import {$utils, $jui} from '@jzl/utils'
import {DFT_ICONS} from "@jzl/icons";

const emit = defineEmits(['select'])
const props = defineProps({
  appId: [Number, String],
  selectedId: [Number, String]
})

const mbtreeRef = ref(null)

const queryText = ref("")
const apps = ref([])
const loading = ref(false)
const selectData = ref(null)
const currentData = ref({})
const actionType = ref('view')     // createGroup | createMb | edit | view
const expandedKeys = ref([])
const treeSetting = ref({
  children: 'subs',
  label: 'name',
  'icon-class': 'hello-icon'
})

const formGroupWinName = ref('')
const formGroupWinShow = ref(false)
const formMbWinName = ref('')
const formMbWinShow = ref(false)

watch(() => queryText.value, (val) => {
  mbtreeRef.value.filter(val)
})

onMounted(() => {
  init();
})

const init = async () => {
  await loadRoot();

  let ids = _.map(apps.value, 'id');
  expandedKeys.value = ids;

  selectDefaultMb();
}

const selectDefaultMb = () => {
  if (selectData.value) return;

  let dftId = props.selectedId;
  if (!dftId) {
    let currentApp = _.find(apps.value, ap => ap.id == props.appId);
    dftId = _.get(currentApp, `subs[0].id`);

    if (!dftId) dftId = _.get(apps.value, `[0].subs[0].id`);
  }
  if (!dftId) return;

  let data = $utils.getTreeData(apps.value, 'id', dftId, 'subs');
  if (data) {
    handleClick(data);
    mbtreeRef.value.setCurrentKey(dftId);
  }
}

const filterNode = (value, data) => {
  if (!value) return true;
  if (!data.name) return true;
  return data.name.indexOf(value) !== -1;
}

const refreshCurrentNode = async (key) => {
  await init();

  let id = _.get(currentData.value, 'id');

  if (key) {
    id = key;
  }

  expandedKeys.value = [id];

  let data = $utils.getTreeData(apps.value, 'id', key, 'subs');

  if (data) {
    handleClick(data);
  }
}

const loadRoot = async () => {
  loading.value = true;

  let iApps = await loadApps();
  let items = await api.mb.getMbTree();

  _.each(iApps, app => {
    let subs = [];

    // 全局
    if (app.id === -100) {
      subs = _.filter(items, {project_id: -1});
    } else if (app.id === -1) {
      subs = _.filter(items, it => {
        return it.app_id === -1 && it.project_id !== -1;
      });
    } else {
      subs = _.filter(items, {app_id: app.id});
    }

    app.subs = subs;
  });

  apps.value = iApps;

  loading.value = false;
}

const loadApps = async () => {
  let ret = await api.admin.getMyApps();
  let myApps = _.get(ret, 'apps', []);
  let apps = [{
    nodeType: 'plat',
    name: '平台内置',
    id: -100
  }, {
    nodeType: 'system',
    name: '系统通用',
    id: -1
  }];

  let xMyApps = _.map(myApps, app => {
    return {
      nodeType: 'app',
      name: `${_.get(app, 'group_name')}-专属`,
      id: _.get(app, 'group_id'),
      isApp: true
    }
  });

  apps = _.concat(apps, xMyApps)

  if (props.appId) {
    apps = _.filter(apps, ap => {
      return ap && (ap.id === props.appId || ap.id < 0)
    });
  }

  return apps;
}

const handleClick = async (data, node, ele) => {
  selectData.value = data;

  if (!data) return;

  if (mbtreeRef.value.store.nodesMap && mbtreeRef.value.store.nodesMap[data.id]) {
    mbtreeRef.value.store.nodesMap[data.id].expanded = true;
  }

  emit("select", data);
}

const handleClearSelect = () => {
  try {
    mbtreeRef.value.setCurrentNode({id: null});
  } catch (e) {
  }
  // currentData.value = null;
  selectData.value = null;
}

const handleShowCreateGroup = () => {
  actionType.value = 'create';     // createGroup | createMb | edit | view

  if (!currentData.value) return;

  if (!isGroup(currentData.value) && !currentData.value.isApp && currentData.value.id != -1) {
    return;
  }

  let name = _.get(currentData.value, 'name');

  formGroupWinName.value = `【${name}】下添加目录`;
  formGroupWinShow.value = true;
}

const handleShowCreateMb = () => {
  actionType.value = 'create';

  let name = _.get(currentData.value, 'name');

  formMbWinName.value = `【${name}】下添加码表`;
  formMbWinShow.value = true;
}

const handleShowEdit = () => {
  let name = _.get(currentData.value, 'name');

  // this.form = _.cloneDeep(currentData.value);
  actionType.value = 'edit';

  // eslint-disable-next-line no-undef
  if ($menuUtils.isGroup(currentData.value)) {
    formGroupWinShow.value = true;
    formGroupWinName.value = `修改目录【${name}】`;
  } else if (this.isMbRoot(currentData.value)) {
    formMbWinShow.value = true;
    formMbWinName.value = `修改码表【${name}】`;
  }
}

const handleShowDelete = () => {

  let dt = currentData.value;

  if (!dt) return;

  let isMbGroup = $menuUtils.isGroup(dt);
  let msg = `确定删除${isMbGroup ? '目录' : '码表'}【${dt.name}】?`;
  $jui.alert(msg).then(async () => {
    let ret = null;
    if (isMbGroup) {
      ret = await api.mb.removeMbGroup(dt.mb_group_id);
    } else {
      ret = await api.mb.removeMb(dt.mb_id);
    }

    let key = '';

    if (isMbGroup) {
      key = `G_${dt.parent_id}`;
    } else {
      if (dt.parent_id) {
        key = `M_${dt.parent_id}`;
      } else {
        key = `G_${dt.mb_group_id}`;
      }
    }

    refreshCurrentNode(key);
  }).catch(e => {

  });
}

const handleTreeCommand = (cmd, data) => {
  currentData.value = data;

  if (cmd === 'cate') {
    handleShowCreateGroup();
  } else if (cmd === 'mb') {
    handleShowCreateMb();
  } else if (cmd === 'edit') {
    handleShowEdit();
  } else if (cmd === 'remove') {
    handleShowDelete();
  }
}

const handleFormClose = (isUpdate) => {
  formGroupWinShow.value = false;
  formMbWinShow.value = false;

  if (isUpdate) {
    refreshCurrentNode();
  }
}

</script>

<template>
  <div class="app-mb-wrap app-cate-menu overflow-hidden">
    <el-input
      v-model="queryText"
      class="thin-search-input"
      clearable
      placeholder="按名称搜索码表"
    />
    <el-scrollbar
      class="mb-tree"
      :settings="{}"
      v-jloading="loading"
      @click="handleClearSelect()">
      <el-tree
        ref="mbtreeRef"
        class="menu-custom-tree"
        :data="apps"
        node-key="id"
        :highlight-current="true"
        :default-expanded-keys="expandedKeys"
        :props="treeSetting"
        :filter-node-method="filterNode"
        @click.native.stop
        @node-click="handleClick">
        <template #default="{ node, data }">
          <span
            class="menu-custom-tree-node"
            style="position: relative;">
            <span
              class="menu-custom-icon"
              :class="{
                'menu-root-icon': isApp(data) || data.id === -100 || data.id === -1,
                'menu-icon-module': isMbRoot(data) && data.type !== 'TREE',
                'menu-icon-api': data.type === 'TREE'
              }"
              v-tippy="{ arrow: true }"
              :content="data.type === 'TREE' ? '树型': '列表型'">
                <!--<i v-if="data.loading" class="el-icon-loading"></i>-->
                <JIcon
                  v-if="data.id === -100"
                  :icon="DFT_ICONS.platform"
                />
                <JIcon
                  v-else-if="data.id === -1"
                  :icon="DFT_ICONS.global"
                />
                <JIcon
                  v-else-if="data.isApp"
                  :icon="DFT_ICONS.app"
                />
                <JIcon
                  v-else-if="isGroup(data)"
                  :icon="DFT_ICONS.dir"
                />
                <template
                  v-else-if="isMbRoot(data)">
                    <JIcon
                      v-if="data.type === 'TREE'"
                      :icon="DFT_ICONS.tree"/>
                    <JIcon
                      v-else
                      :icon="DFT_ICONS.mb"
                    />
                  <!--<img src="/assets/images/filetype/small/GeneralType.png" />-->
                </template>
                <JIcon
                  v-else
                  :icon="DFT_ICONS.fileLocal"
                />
            </span>
            <span v-text="data.name"></span>
            <div @click.stop v-if="canEdit(data)">
                <el-dropdown
                  trigger="click"
                  placement="bottom-start"
                  size="small"
                  style="position:absolute;right: 0px;"
                  @command="handleTreeCommand($event, data)">
                  <JIcon
                    class="btn-more"
                    :icon="DFT_ICONS.more"
                    v-tippy="{ arrow: true }"
                    content="更多操作"/>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <!--<el-dropdown-item><i class="el-icon-plus"></i>分组</el-dropdown-item>
                      <el-dropdown-item><i class="el-icon-plus"></i>菜单</el-dropdown-item>-->
                      <template v-if="data.id === -100 || data.id === -1 || data.isApp || isGroup(data)">
                        <el-dropdown-item
                          command="cate">
                          <JIcon
                            :icon="DFT_ICONS.add"
                          />分类</el-dropdown-item>
                        <el-dropdown-item
                          command="mb">
                          <JIcon
                            :icon="DFT_ICONS.add"
                          />码表</el-dropdown-item>
                      </template>
                      <template v-if="isGroup(data) || isMbRoot(data)">
                        <el-dropdown-item
                          command="edit">
                          <JIcon
                            :icon="DFT_ICONS.edit"
                          />修改</el-dropdown-item>
                        <el-dropdown-item
                          command="remove">
                          <JIcon
                            :icon="DFT_ICONS.delete"
                          />删除</el-dropdown-item>
                      </template>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
            </div>
          </span>
        </template>
      </el-tree>

      <el-dialog
        v-model="formGroupWinShow"
        :title="formGroupWinName"
        :close-on-click-modal="false"
        :append-to-body="true">
        <mbform-group
          v-if="formGroupWinShow"
          :current-data="currentData"
          :action-type="actionType"
          @close="handleFormClose"></mbform-group>
      </el-dialog>

      <el-dialog
        v-model="formMbWinShow"
        :title="formMbWinName"
        :close-on-click-modal="false"
        :append-to-body="true">
        <mbform-mb
          v-if="formMbWinShow"
          :current-data="currentData"
          :action-type="actionType"
          @close="handleFormClose"></mbform-mb>
      </el-dialog>
    </el-scrollbar>
  </div>
</template>

<style lang="scss" scoped>
.app-mb-wrap {
  display: flex;
  flex-flow: column;
  z-index: 1;
  //box-shadow: 0 0 5px var(--j-border-color);
}

.mb-info {
  display: flex;
  flex-flow: column;
  padding: 10px;
  flex: 1;

  .m-table-container {
    flex: 1;
    height: 100%;
  }
}
</style>
